import sys
import os
import time
import paho.mqtt.client as mqtt
from app01 import models
from threading import Thread



sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
sys.path.append("..")


def on_connect(client, userdata, flags, rc):
    print('connected to mqtt with resurt code ', rc)
    client.subscribe("test2")



def on_message(client, userdata, msg):
        msg.payload=str(msg.payload)
        data=msg.payload[3:-1].split(',')
        index=msg.payload.find("+")
        cmd=msg.payload[2:index]
        models.Equipment.objects.filter(MAC=cmd).update(status=1)
        # 收到消息后执行任务
        if models.Iot01.objects.filter(id=1).first().MAC==cmd:
            models.Iot01.objects.create(Temp=float(int(data[0])),Hum=float(int(data[1])))
        elif models.Iot3.objects.filter(id=1).first().MAC==cmd:
            models.Iot3.objects.create(PM10=float(int(data[0])),PM25=float(int(data[1])))

def mqttfunction():
    # print(msg)
    global client

    models.Equipment.objects.all().update(status=2)
    client.loop_forever(retry_first_connection=True)


def server_conenet(client):
    client.on_connect = on_connect  # 启用订阅模式
    client.on_message = on_message  # 接收消息
    client.connect("127.0.0.1", 1883, 600)  # 链接
    mqttthread = Thread(target=mqttfunction)
    mqttthread.start()
    # client.loop_forever(retry_first_connection=True)



def server_stop(client):
    client.loop_stop()  # 停止服务端
    sys.exit(0)


def server_main():
    global client
    client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    client = mqtt.Client(client_id, transport='tcp')
    server_conenet(client)


if __name__ == '__main__':
    # 启动监听

    server_main()